package com.chen.web;

import com.chen.pojo.Customer;
import com.chen.pojo.PageBean;
import com.chen.service.CustomerService;
import com.chen.utils.ResponseUtil;
import com.chen.utils.StringUtil;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * com.example.demo.controller
 * 作者      : 陈晓
 * 描述      :
 * 创建日期  : 2018/4/27
 * 修改日期  :
 */

@Controller
@RequestMapping("/customer")
public class CustomerController {

  @Autowired
  private CustomerService customerService;
  private Logger logger = Logger.getLogger(CustomerController.class);
  private static final String page = "customer/customerList";
  private static final String page1 = "customer/ceshi";


  @RequestMapping("/index")
  public String index() {
    System.out.println("====进入客户信息管理中心页面=====");
    return page;
  }

  /**
   * 获得客户信息列表
   * @param customer
   * @param response
   * @param request
   * @return
   */
  @RequestMapping("/list")
  public String list(Customer customer,HttpServletResponse response,HttpServletRequest request) {
    System.out.println("====进入客户信息管理获得列表信息界面=====");
JSONObject result = new JSONObject();
    PageBean pageBean = new PageBean();
    String page = request.getParameter("page");
    String rows = request.getParameter("rows");
    if (StringUtil.isNotEmpty(page) && StringUtil.isNotEmpty(rows)) {
      pageBean.setPage(Integer.parseInt(page));
      pageBean.setPageSize(Integer.parseInt(rows));
    }
    try {
      List<Customer> list = customerService.getList(customer, pageBean);
      long count = customerService.getCount(customer);
      result.put("rows", list);
      result.put("total", count);
      ResponseUtil.write(response, result);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }

  /**
   * 客户信息的添加保存
   * @param customer 客户信息
   * @param response
   * @param request
   * @return
   */
  @RequestMapping("/save")
  @ResponseBody
  public String save( Customer customer, HttpServletResponse response, HttpServletRequest request) {
    JSONObject result = new JSONObject();
    String message = "客户添加成功!!!";
      try {
        customerService.insert(customer);
        result.put("success",true);
        result.put("message",message);
      } catch (Exception e) {
        result.put("success",false);
        result.put("message","客户添加失败!!!");
        ResponseUtil.write(response, result);
        logger.error(e.getCause().getMessage());
        e.printStackTrace();
      }
    ResponseUtil.write(response, result);
    return null;
  }
}
